// 从URL中获取FastMoss产品ID
function getFastMossProductId() {
  const url = window.location.href;
  const match = url.match(/\/detail\/(\d+)(?:#|$)/);
  return match ? match[1] : null;
}

function extractFastmossProductDescription() {
  // 提取店铺描述文本
  const textNodes = document.evaluate(
    '//*[@id="myDiv"]/div/span[1]//text()',
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null
  );

  let description = '';
  for (let i = 0; i < textNodes.snapshotLength; i++) {
    description += textNodes.snapshotItem(i).nodeValue.trim() + ' ';
  }

  return description.trim();
}


function extractFastmossProductBasicInfo() {
  const titleNode = getNodeByXPath('//*[@id="container"]/div[2]/div[2]/main/div/div[1]/div[2]/div[2]/div/div/div[1]/div[1]/div/div/span');
  const title = extractTextFromNode(titleNode);
  const categoryNode = getNodeByXPath('//*[@id="container"]/div[2]/div[2]/main/div/div[1]/div[2]/div[2]/div/div/div[2]/div[2]/span');
  const category = extractTextFromNode(categoryNode);

    // 获取基本信息键值对
  const containerXPath = "//*[@id=\"container\"]/div[2]/div[2]/main/div/div/div[1]/div[2]/div[1]/div[2]/div";
  const keyValuePairs = extractKeyValuePairs(
    containerXPath,
    "./div[1]",
    "./div[2]"
  );

  return {
    title,
    category
  };
}

function extractFastmossProductOverall() {
  const result = {};
  
  // 提取主要数据
  const xpath_overall = '//*[@id="container"]/div[2]/div[2]/main/div/div[1]/div[2]/div[2]/div/div/div[3]/div/div/div/div[1]/div'
                         //*[@id="container"]/div[2]/div[2]/main/div/div[1]/div[2]/div[2]/div/div/div[3]/div/div/div/div[1]/div[5]/div/div[2]/div/div
  const mainDivs = getNodesByXPath(`${xpath_overall}`);
  
  for (let i = 0; i < mainDivs.snapshotLength; i++) {
    const div = mainDivs.snapshotItem(i);
    
    // 尝试两种可能的key节点路径
    let keyNode = getNodeByXPath('./div[1]/div/div[2]', div);
    let valueNode = getNodeByXPath('./div/div[1]/div', div);

    if (keyNode && valueNode) {
      result[getAllTextContent(keyNode)] = extractNumberFromNode(valueNode);
      continue;
    }
    
    // 尝试两种可能的key节点路径
    keyNode = getNodeByXPath('./div/div[2]/div[2]/div', div);
    valueNode = getNodeByXPath('./div/div[1]/div', div);

    if (keyNode && valueNode) {
      result[getAllTextContent(keyNode)] = extractNumberFromNode(valueNode);
      continue;
    }
    
    // 尝试两种可能的key节点路径
    keyNode = getNodeByXPath('./div/div[2]/div/div', div);
    valueNode = getNodeByXPath('./div/div[1]/div', div);

    if (keyNode && valueNode) {
      result[getAllTextContent(keyNode)] = extractNumberFromNode(valueNode);
      continue;
    }
  }

  // 提取额外数据
  const additionalXPath = '//*[@id="container"]/div[2]/div[2]/main/div/div[1]/div[2]/div[2]/div/div/div[3]/div/div/div/div[2]/div[1]/div'
                           //*[@id="container"]/div[2]/div[2]/main/div/div[1]/div[2]/div[2]/div/div/div[3]/div/div/div/div[2]/div[1]/div
  const additionalDivs = getNodesByXPath(additionalXPath);

  for (let i = 0; i < additionalDivs.snapshotLength; i++) {
    const div = additionalDivs.snapshotItem(i);
    let keyNode = getNodeByXPath("./span[1]", div);
    let valueNode = getNodeByXPath("./span[2]", div);

    if (keyNode && valueNode) {
      result[getAllTextContent(keyNode)] = extractNumberFromNode(valueNode);
      continue;
    }

    keyNode = getNodeByXPath("./span[1]", div);
    valueNode = getNodeByXPath("./div[1]/span[2]", div);

    if (keyNode && valueNode) {
      result[getAllTextContent(keyNode)] = extractNumberFromNode(valueNode);
      continue;
    }

  }

  // Check and rename empty or $ prefixed fields
  for (const [key, value] of Object.entries(result)) {
    if (key === '' || key.startsWith('$')) {
      delete result[key];
      result['价格'] = value;
    }
  }

  // Process price field if it exists
  if (result['价格']) {
    const priceValue = result['价格'];
    // Check if price is in format "$X.XX - Y.YY"
    const rangeMatch = String(priceValue).match(/^\$?([\d.]+)\s*-\s*([\d.]+)$/);
    if (rangeMatch) {
      result['价格'] = parseFloat(rangeMatch[1]);
      result['价格H'] = parseFloat(rangeMatch[2]);
    } else if (!isNaN(priceValue)) {
      // If already a number, set both fields to same value
      result['价格H'] = parseFloat(priceValue);
    }
  }

  // 获取店铺名称
  const storeNameNode = getNodeByXPath('//*[@id="container"]/div[2]/div[2]/main/div[2]/div[1]/div[2]/div[2]/div/div/div[3]/div/div/div/div[2]/a/div/div[2]/div[2]');
  if (storeNameNode) {
    result['店铺名称'] = extractTextFromNode(storeNameNode);
  }

  // 获取店铺类目
  const storeCategoryNode = getNodeByXPath('//*[@id="container"]/div[2]/div[2]/main/div[2]/div[1]/div[2]/div[2]/div/div/div[3]/div/div/div/div[2]/a/div/div[2]/div[3]/span');
  if (storeCategoryNode) {
    result['店铺类目'] = extractTextFromNode(storeCategoryNode);
  }

  return result;
}


/**
 * Extracts product details from Fastmoss data.
 * @returns {Object} An object containing the extracted product details.
 */
function extractFastmossProductDataOverview() {
  // 数据总览
  return  extractKeyValuePairs(
    '//*[@id="overview"]/div[1]/div[2]/div/div/div/div/div/div[1]/div[1]/div/label/span[2]/div',
    './div[2]/p[1]',
    './div[1]/p[1]'
  );
}

function extractFastmossProductDealAnalysis() {
  // 成交渠道占比 和 成交内容占比
  // 成交渠道占比
  const dealChannel = extractKeyValuePairs(
    '//*[@id="overview"]/div[2]/div/div/div/div[1]/div/div/div/div[2]/div/div[2]/div[position()>1]',
    './div[1]/div[1]/span',
    './div[2]/span'
  );

  // 提取交易方式数据
  const dealManner = extractKeyValuePairs(
    '//*[@id="overview"]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div/div[2]/div[position()>1]',
    './div[1]/div[1]/span',
    './div[2]/span'
  );

  return { dealChannel, dealManner };
}

function extractFastmossProductVideoList() {
  // 商品关联视频
  const headerXPath = '//*[@id="related_videos"]/div[2]/div[2]/div/div/div/div/div/div/div/div/table/thead/tr/th';
  const rowXPath = '//*[@id="related_videos"]/div[2]/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr[position()>1]';
  
  return extractTableData(headerXPath, rowXPath);
}

function extractFastmossProductLiveStreamList() {
  // 商品关联直播
  const headerXPath = '//*[@id="related_lives"]/div[2]/div[2]/div/div/div/div/div/div/div/div/table/thead/tr/th';
  const rowXPath = '//*[@id="related_lives"]/div[2]/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr[position()>1]';
  
  return extractTableData(headerXPath, rowXPath);
}

function extractFastmossProductInfluencerList() {
  // 商品关联达人
  const headerXPath = '//*[@id="related_creators"]/div[2]/div[2]/div[2]/div/div/div/div/div/div/div/div/table/thead/tr/th';
  const rowXPath = '//*[@id="related_creators"]/div[2]/div[2]/div[2]/div/div/div/div/div/div/div/div/table/tbody/tr[position()>1]';
  
  return extractTableData(headerXPath, rowXPath);
}

function extractFastmossProductReviewSummaryList() {
  // 商品关联达人
  const headerXPath = '//*[@id="ai_comments"]/div[2]/div[3]/div[2]/div/div/div/div/div/div/div/div[1]/table/thead/tr/th';
  const rowXPath = '//*[@id="ai_comments"]/div[2]/div[3]/div[2]/div/div/div/div/div/div/div/div[2]/table/tbody/tr[position()>1]';
  
  return extractTableData(headerXPath, rowXPath);
}

export {
  getFastMossProductId,
  extractFastmossProductDescription,
  extractFastmossProductBasicInfo,
  extractFastmossProductOverall,
  extractFastmossProductDataOverview,
  extractFastmossProductDealAnalysis,
  extractFastmossProductVideoList,
  extractFastmossProductLiveStreamList,
  extractFastmossProductInfluencerList,
  extractFastmossProductReviewSummaryList
};
